package com.kangzhili.aicoder.ai.tools;

import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * LangChain4j 工具类：从指定URL获取Java面试题并按关键词筛选
 */
@Slf4j
public class InterviewQuestionTool {

    // 面试题Markdown源地址
    private static final String QUESTIONS_URL =
            "https://gitee.com/kangzhili/document/raw/master/Java%E7%83%AD%E9%97%A8%E9%9D%A2%E8%AF%95%E9%A2%98100%E9%A2%98.md";

    // 匹配Markdown中的面试题格式（数字. **题目**）
    private static final Pattern QUESTION_PATTERN = Pattern.compile("(\\d+)\\.\\s*\\*\\*(.*?)\\*\\*");

    /**
     * LangChain4j工具方法：根据关键词获取相关面试题
     * @param keyword 搜索关键词（如"多线程"、"集合"）
     * @return 匹配的面试题列表
     */
    @Tool("获取与关键词相关的Java面试题，返回匹配的题目列表")
    public String fetchQuestionsByKeyword(String keyword) {
        try {
            log.info("调用LangChain4j工具类：从指定URL获取Java面试题并按关键词筛选");
            // 1. 从URL获取Markdown内容
            String markdownContent = fetchUrlContent(QUESTIONS_URL);
            if (markdownContent.isEmpty()) {
                return "无法获取面试题资源，请检查网络连接";
            }

            // 2. 解析所有面试题
            List<Question> allQuestions = parseQuestions(markdownContent);
            if (allQuestions.isEmpty()) {
                return "未解析到任何面试题";
            }

            // 3. 按关键词筛选
            List<Question> matchedQuestions = filterByKeyword(allQuestions, keyword);

            // 4. 格式化返回结果
            return formatResult(matchedQuestions, keyword);

        } catch (Exception e) {
            return "获取面试题失败：" + e.getMessage();
        }
    }

    /**
     * 从URL获取内容
     */
    private String fetchUrlContent(String urlString) throws IOException {
        StringBuilder content = new StringBuilder();
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        // 设置请求头模拟浏览器，避免被拦截
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }

    /**
     * 解析Markdown内容提取面试题
     */
    private List<Question> parseQuestions(String content) {
        List<Question> questions = new ArrayList<>();
        Matcher matcher = QUESTION_PATTERN.matcher(content);

        while (matcher.find()) {
            int number = Integer.parseInt(matcher.group(1));
            String text = matcher.group(2).trim();
            questions.add(new Question(number, text));
        }
        return questions;
    }

    /**
     * 按关键词筛选面试题
     */
    private List<Question> filterByKeyword(List<Question> questions, String keyword) {
        List<Question> matched = new ArrayList<>();
        if (keyword == null || keyword.trim().isEmpty()) {
            return questions; // 关键词为空时返回所有题目
        }

        String lowerKeyword = keyword.toLowerCase();
        for (Question q : questions) {
            if (q.text.toLowerCase().contains(lowerKeyword)) {
                matched.add(q);
            }
        }
        return matched;
    }

    /**
     * 格式化返回结果
     */
    private String formatResult(List<Question> questions, String keyword) {
        if (questions.isEmpty()) {
            return "未找到与 [" + keyword + "] 相关的面试题";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("找到 ").append(questions.size()).append(" 道与 [").append(keyword).append("] 相关的面试题：\n");
        for (Question q : questions) {
            sb.append(q.number).append(". ").append(q.text).append("\n");
        }
        return sb.toString();
    }

    /**
     * 面试题实体类
     */
    private static class Question {
        int number;
        String text;

        Question(int number, String text) {
            this.number = number;
            this.text = text;
        }
    }
}
